package org.huanletao.ssm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * </p>
 * package: org.huanletao.ssm.util
 * description:
 * className: TreeUtils
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/9/4 16:21
 * since: 1.0.0
 */
public abstract class TreeUtils {

    /**
     * 通过接口构建树形结构数据
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode<T>> List<T> buildTree(List<T> treeNodes) {
        List<T> treeRootNode = TreeUtils.getTreeRootNode(treeNodes);
        for (T treeNode : treeRootNode) {
            buildTree(treeNode, treeNodes);
        }
        return treeRootNode;
    }

    /**
     * @param treeNode
     * @param treeNodes
     */
    private static <T extends TreeNode<T>> void buildTree(T treeNode, List<T> treeNodes) {
        List<T> nodeChildList = getTreeNodeChildList(treeNode, treeNodes);
        //递归终止条件，
        if (nodeChildList.isEmpty()) return;
        treeNode.setTreeChildrenNode(nodeChildList);
        for (T treeNodec : nodeChildList) {
            buildTree(treeNodec, treeNodes);
        }
    }

    /**
     * @param treeNode
     * @param treeNodes
     * @return
     */
    private static <T extends TreeNode<T>> List<T> getTreeNodeChildList(T treeNode, List<T> treeNodes) {
        List<T> sysMenuList = new ArrayList<>();
        for (T treeNodec : treeNodes) {
            if (treeNodec.getParentId().equals(treeNode.getId())) {
                sysMenuList.add(treeNodec);
            }
        }
        return sysMenuList;
    }

    /**
     * @param treeNodes
     * @return
     */
    private static <T extends TreeNode<T>> List<T> getTreeRootNode(List<T> treeNodes) {
        return treeNodes.stream().filter(treeNode -> 0L == treeNode.getParentId()).collect(Collectors.toList());
    }
}
